using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FPBulletMover_Tutorial : MonoBehaviour
{
    private float speed;
    private float startTime = -1;
    private Vector3 moveDir;

    private Transform selfTrans;
    private Transform muzzleTrans;

    private bool initialized = false;
    private WindManager_Tutorial windManager;

    public void Initialization(Transform _muzzle, float _bulletSpeed, WindManager_Tutorial _windManager)
    {
        speed = _bulletSpeed;
        muzzleTrans = _muzzle;
        moveDir = _muzzle.forward;
        selfTrans = transform;
        initialized = true;
        windManager = _windManager;
    }

    private void FixedUpdate()
    {
        if (startTime < 0) startTime = Time.time;
        var tmp_CurTime = Time.time - startTime;
        var tmp_PreTime = tmp_CurTime - Time.fixedDeltaTime;
        var tmp_NextTime = tmp_CurTime + Time.fixedDeltaTime;
        var tmp_CurPoint = GetBulletPoint(tmp_CurTime);
        RaycastHit tmp_Hit;
        if (tmp_PreTime > 0)
        {
            var tmp_PrePoint = GetBulletPoint(tmp_PreTime);
            //TODO:物理检测
            if (Physics.Linecast(tmp_PrePoint, tmp_CurPoint, out tmp_Hit))
            {
                OnHit(tmp_Hit);
            }
        }


        var tmp_NextPoint = GetBulletPoint(tmp_NextTime);
        //TODO:物理检测
        if (Physics.Linecast(tmp_CurPoint, tmp_NextPoint, out tmp_Hit))
        {
            OnHit(tmp_Hit);
        }

        Debug.DrawRay(tmp_CurPoint, tmp_NextPoint - tmp_CurPoint, Color.red, 5);
    }


    private void OnHit(RaycastHit _hit)
    {
        _hit.collider.GetComponentInParent<ShootableObject>()?.OnHit(_hit);
    }


    private void Update()
    {
        if (!initialized || startTime < 0) return;
        //TODO:更新Transform的位置
        var tmp_CurTime = Time.time - startTime;
        var tmp_CurPoint = GetBulletPoint(tmp_CurTime);
        selfTrans.position = tmp_CurPoint;
    }


    private Vector3 GetBulletPoint(float _time)
    {
        //vt
        var tmp_HorizontalSpeed = _time * speed * moveDir + selfTrans.position;
        //gt^2
        var tmp_GravityVector = 9.81f * _time * _time * Vector3.down;
        //Wind 
        var tmp_WindVector = _time * _time * windManager.GetWindValue;


        return tmp_HorizontalSpeed + tmp_GravityVector + tmp_WindVector;
    }
}